﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;


namespace WeiTap.Restful.ApiContext
{
    public sealed class ApiContext:Container
    {
        public static ApiContext Current => (ApiContext) ApiContextManager.Container;
        private WebApi _api;

        internal ApiContext(WebApi api)
        {
            _api = api;
            ApiContextManager.SetContainer(this);
        }

        public IWebApi WebApi => _api;
        private string _requestId;

        private const string HttpRequestId = "WebApi.RequestID";
        private const string SysPrevLogId = "WebApi.Prev_Log_Id";
        private const string SysLogId = "WebApi.Request_Log_Id";
        private string _logId;
        public string RequestId
        {
            get { return _requestId; }
            set
            {
                _requestId = value;
                CallContext.LogicalSetData(HttpRequestId, value);
                Trace.WriteLine((object)value, HttpRequestId);
            }
        }
        /// <summary>
        /// 日志ID
        /// </summary>
        public string LogId
        {
            get { return _logId; }
            set
            {
                _logId = value;
                if (string.IsNullOrWhiteSpace(value) == false)
                {
                    Trace.WriteLine((object)value, SysLogId);
                    CallContext.LogicalSetData(SysLogId, value);
                }
            }
        }
        private string _prevLogId;
        /// <summary>
        /// 日志ID
        /// </summary>
        public string PrevLogId
        {
            get { return _prevLogId; }
            set
            {
                _prevLogId = value;
                if (string.IsNullOrWhiteSpace(value) == false)
                {
                    Trace.WriteLine((object)value, SysPrevLogId);
                }
            }
        }
        /// <summary>
        /// 销毁上下文
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (disposing)
            {
                ApiContextManager.Dispose();
                Trace.Flush();
            }
        }
    }
}
